local LUF = LibStub("AceAddon-3.0"):GetAddon("lUnitFrame")
local db
local options 
local buff={"party1","party2","party3","party4"}


local MODNAME = "Buff"
local mod = LUF:NewModule(MODNAME, "AceEvent-3.0")



local function getOptions()
	if not options then
		options ={
			type = "group",
			name = MODNAME,
			args = {
				enable ={
					type = "toggle",
					name = "enable",
					get = function() return db.enable end,
					set = function(info,v) db.enable = v end,
				}
			}
		}
	end
	return options
end

function mod:OnInitialize()
	self.db = LUF.db:RegisterNamespace(MODNAME)
    self.db:RegisterDefaults({
        profile = {
			enable = true;
			
        },
    })
	db = self.db.profile
	LUF:RegisterModuleOptions(MODNAME, getOptions)
	for _ , v in pairs(buff) do
		self:CreateBuff(v)
	end
	
	
	
	
end



function mod:OnEnable()
	LUF.Print(MODNAME.." is loaded")
    self:RegisterEvent("UNIT_AURA")
	self:RegisterEvent("PARTY_MEMBERS_CHANGED","UpdateUnit");
	self:UpdateUnit()
end

function mod:CreateBuff(unit)
	local frame=LUF.frames[unit]
	frame.buff={}
	for i = 1,16 do
		local buff = CreateFrame("Button",frame:GetName().."LufBuff"..i,frame,"PartyBuffButtonTemplate");
		_G[buff:GetName().."Border"]:Hide();
		buff:SetID(i);
		buff:SetScript("OnEnter",function()
			GameTooltip:SetOwner(this, "ANCHOR_BOTTOMRIGHT", 15, -25)
			GameTooltip:SetUnitBuff("party"..this:GetParent():GetID(), this:GetID())
			end
		)
		frame.buff[i]=buff
		if i == 1 then
			buff:SetPoint("TOPLEFT", frame, "TOPLEFT", 48, -32)
		else
			buff:SetPoint("LEFT", frame.buff[i-1], "RIGHT", 2, 0)
		end
		buff:Hide()
	end
	local debuff1 = _G[frame:GetName().."Debuff1"]
	debuff1:ClearAllPoints()
	debuff1:SetPoint("LEFT",frame , "RIGHT", 22, 28)

end

function mod:UpdateUnitBuff(unit)
	local frame = LUF.frames[unit];
	for i = 1,16 do 
		local _ ,_ ,bufftex = UnitBuff(unit,i);
		if bufftex then
			_G[frame.buff[i]:GetName().."Icon"]:SetTexture(bufftex);
			frame.buff[i]:Show()
		else 
			frame.buff[i]:Hide()
		end
	end
end

function mod:UNIT_AURA()
	for _,v in pairs(buff) do
		if arg1 == v then
			self:UpdateUnitBuff(arg1)
			return
		end
	end
end

function mod:UpdateUnit()
	for _,v in pairs(buff) do
		self:UpdateUnitBuff(v)
	end
end


